<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :destroyOnClose="true"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">

        <a-form-model-item label="栏目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
          <a-input v-model="model.name" placeholder="请输入栏目名称"></a-input>
        </a-form-model-item>

        <j-editable-table
          v-if="title==='编辑'"
          ref="editableTable"
          :loading="loading"
          :columns="columns"
          :dataSource="dataSource"
          :rowNumber="true"
          :dragSort="true"
          style="margin-top: 8px;"
        >
        </j-editable-table>


      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import JTreeSelect from '@/components/jeecg/JTreeSelect'
  import JEditableTable from '@/components/jeecg/JEditableTable'
  import {
    FormTypes,
    VALIDATE_NO_PASSED,
    getRefPromise,
    validateFormModelAndTables
  } from '@/utils/JEditableTableUtil'

  export default {
    name: 'ChannelModal',
    components: {
      JTreeSelect, JEditableTable
    },
    data() {
      return {
        dataSource: [],
        loading: false,
        title: '操作',
        width: 1200,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },

        confirmLoading: false,
        validatorRules: {
          pid: {},
          name: [{ required: true, message: '请输入栏目名称!' }]
        },
        url: {
          add: '/cms/channel/add',
          edit: '/cms/channel/edit',
          checkCode: '/cms/channel/checkCode'
        },
        expandedRowKeys: [],
        pidField: 'pid',
        subExpandedKeys: [],
        columns: [
          {
            title: '是否表字段',
            key: 'isTransient',
            width: '5%',
            type: FormTypes.hidden,
            defaultChecked: true,
            customValue: [true, false]
          },
          {
            title: '字段名称',
            key: 'columnName',
            width: '18%',
            type: FormTypes.input,
            defaultValue: '',
            placeholder: '请输入${title}',
            disabled: true
          },
          {
            title: '字段描述',
            key: 'columnComment',
            width: '10%',
            type: FormTypes.input,
            defaultValue: '',
            placeholder: '请输入${title}'
          },
          {
            title: '表单显示',
            key: 'isInsert',
            width: '5%',
            type: FormTypes.checkbox,
            customValue: [true, false]
          },
          {
            title: '列表显示',
            key: 'isList',
            width: '5%',
            type: FormTypes.checkbox,
            customValue: [true, false]
          },
          {
            title: '是否查询',
            key: 'isQuery',
            width: '5%',
            type: FormTypes.checkbox,
            customValue: [true, false]
          },
          {
            title: '是否唯一',
            key: 'isIncrement',
            width: '5%',
            type: FormTypes.checkbox,
            customValue: [true, false]
          },
          {
            title: '是否必填',
            key: 'isRequired',
            width: '5%',
            type: FormTypes.checkbox,
            customValue: [true, false]
          },
          {
            title: '控件类型',
            key: 'htmlType',
            width: '18%',
            type: FormTypes.select,
            options: [ // 下拉选项
              { title: '文本框', value: 'input' },
              { title: '多行文本', value: 'textarea' },
              { title: '下拉框', value: 'select' },
              { title: '单选框', value: 'radio' },
              { title: '多选框', value: 'checkbox' },
              { title: '日期(yyyy-MM-dd)', value: 'date' },
              { title: '日期(yyyy-MM-dd HH:mm:ss)', value: 'datetime' },
              { title: '会员选择', value: 'sel_member' },
              { title: '视频选择', value: 'sel_video' },
              { title: '链接选择', value: 'sel_link' },
              { title: '文件', value: 'file' },
              { title: '图片', value: 'image' },
              { title: '开关', value: 'switch' },
              { title: '省市区联动', value: 'pca' },
              { title: '分类字典树', value: 'cat_tree' },
              { title: '密码', value: 'INT' },
              { title: '富文本', value: 'editor' }
            ],
            allowInput: true,
            defaultValue: 'input',
            placeholder: '请选择${title}'
          },
          {
            title: '验证规则',
            key: 'fieldValid',
            type: FormTypes.select,
            options: [ // 下拉选项
              { title: '数字', value: 'n' },
              { title: '字母', value: 's' },
              { title: '整数', value: 'z' }
            ],
            allowInput: true,
            defaultValue: '',
            placeholder: '请选择${title}'
          },
          {
            title: '控件长度',
            key: 'fieldLength',
            type: FormTypes.inputNumber,
            defaultValue: '',
            placeholder: '请选择${title}'
          },
          {
            title: '文件格式',
            key: 'accept',
            type: FormTypes.input,
            defaultValue: '',
            placeholder: '请输入${title}',
          },
          {
            title: '是否启用',
            key: 'status',
            width: '5%',
            type: FormTypes.checkbox,
            customValue: [true, false]
          }
        ]

      }
    },
    created() {
    },
    computed: {
      disabled() {
        return this.model.id ? true : false
      }
    },
    methods: {
      test(t) {
        console.log(t)
      },
      handleSelectRowChange(selectedRowIds) {
        this.selectedRowIds = selectedRowIds
      },
      add() {
        this.edit({ level: 0 })
      },
      edit(record) {
        this.model = Object.assign({}, record)
        this.visible = true
        getAction('/cms/channel/queryColumnList?channelCode=' + record.code).then((res) => {
          if (res.success) {
            this.dataSource = res.result
          }
        }).catch(e => {

        })
      },
      close() {
        this.$emit('close')
        this.visible = false
        this.$refs.form.resetFields()
      },
      handleOk() {
        const that = this

        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true
            let httpurl = ''
            let method = 'post'
            if (!this.model.id) {
              httpurl += this.url.add
              httpAction(httpurl, this.model, method).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  // close的时候清空了表单的值 导致model为空 修改值在列表页没有变 此处需要复制一下model
                  that.submitSuccess({ ...this.model })
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.confirmLoading = false
                that.close()
              })
            } else {
              this.$refs.editableTable.getValues((error, values) => {
                this.model.tableColumnList = values
                httpurl += this.url.edit
                httpAction(httpurl, this.model, method).then((res) => {
                  if (res.success) {
                    that.$message.success(res.message)
                    // close的时候清空了表单的值 导致model为空 修改值在列表页没有变 此处需要复制一下model
                    that.submitSuccess({ ...this.model })
                  } else {
                    that.$message.warning(res.message)
                  }
                }).finally(() => {
                  that.confirmLoading = false
                  that.close()
                })
              })
            }
          } else {
            return false
          }

        })

      },
      handleCancel() {
        this.close()
      },
      submitSuccess(formData) {
        this.$emit('ok', formData)
        /* if(!formData.id){
           let treeData = this.$refs.treeSelect.getCurrTreeData()
           this.expandedRowKeys=[]
           this.getExpandKeysByPid(formData[this.pidField],treeData,treeData)
           if(formData.pid && this.expandedRowKeys.length==0){
             this.expandedRowKeys = this.subExpandedKeys;
           }
           this.$emit('ok',formData,this.expandedRowKeys.reverse());
         }else{
           this.$emit('ok',formData);
       }*/
      },
      getExpandKeysByPid(pid, arr, all) {
        if (pid && arr && arr.length > 0) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].key == pid) {
              this.expandedRowKeys.push(arr[i].key)
              this.getExpandKeysByPid(arr[i]['parentId'], all, all)
            } else {
              this.getExpandKeysByPid(pid, arr[i].children, all)
            }
          }
        }
      }

    }
  }
</script>